<template>
  <div class="sales-ranking-container">
    <el-card class="box-card">
             <template #header>
         <div class="card-header">
           <span>今日代理销量排行榜</span>
          <div>
            <el-button type="primary" @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
            <el-button type="success" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
          </div>
        </div>
      </template>

      <!-- 查询条件 -->
      <div class="search-box">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleDateRangeChange"
              clearable
            />
          </el-form-item>
          <el-form-item label="统计周期">
            <el-select
              v-model="queryParams.period"
              placeholder="选择统计周期"
              @change="handleQuery"
            >
              <el-option label="今日" value="today" />
              <el-option label="本周" value="week" />
              <el-option label="本月" value="month" />
              <el-option label="本季度" value="quarter" />
              <el-option label="本年" value="year" />
              <el-option label="全部" value="all" />
            </el-select>
          </el-form-item>
          <el-form-item label="显示数量">
            <el-select
              v-model="queryParams.limit"
              placeholder="显示数量"
              @change="handleQuery"
            >
              <el-option label="前5名" :value="5" />
              <el-option label="前10名" :value="10" />
              <el-option label="前20名" :value="20" />
              <el-option label="前50名" :value="50" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 统计概览 -->
      <div class="stats-overview">
                 <el-row :gutter="20">
           <el-col :span="8">
             <el-statistic title="总代理数" :value="overviewStats.totalAgents" />
           </el-col>
           <el-col :span="8">
             <el-statistic
               title="今日总销量"
               :value="overviewStats.totalSales"
               suffix="单"
             />
           </el-col>
           <el-col :span="8">
             <el-statistic
               title="今日平均销量"
               :value="overviewStats.avgSales"
               suffix="单"
               :precision="1"
             />
           </el-col>
         </el-row>
      </div>

      <!-- 排行榜表格 -->
      <div class="ranking-table">
        <el-table v-loading="loading" :data="rankingList" stripe>
          <el-table-column label="排名" width="80" align="center">
            <template #default="scope">
              <div class="ranking-badge">
                <el-icon v-if="scope.$index === 0" class="gold-medal" size="20">
                  <Trophy />
                </el-icon>
                <el-icon
                  v-else-if="scope.$index === 1"
                  class="silver-medal"
                  size="20"
                >
                  <Medal />
                </el-icon>
                <el-icon
                  v-else-if="scope.$index === 2"
                  class="bronze-medal"
                  size="20"
                >
                  <Medal />
                </el-icon>
                <span v-else class="rank-number">{{ scope.$index + 1 }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="agent_name" label="代理名称" min-width="150">
            <template #default="scope">
              <div class="agent-info">
                <el-avatar
                  :size="32"
                  :src="scope.row.avatar"
                  :alt="scope.row.agent_name"
                >
                  {{ scope.row.agent_name.substring(0, 1) }}
                </el-avatar>
                <div class="agent-details">
                  <div class="agent-name">{{ scope.row.agent_name }}</div>
                  <div class="agent-level">{{ scope.row.level_name }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="sales_count"
            label="今日销售数量"
            width="200"
            align="center"
            sortable
          >
            <template #default="scope">
              <div class="sales-highlight">
                <div 
                  class="sales-number"
                  :class="getSalesNumberClass(scope.$index)"
                >
                  {{ scope.row.sales_count }}
                </div>
                <div class="sales-unit">单</div>
              </div>
              <div class="sales-note">一张卡密 = 一单</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="conversion_rate"
            label="转化率"
            width="100"
            align="center"
          >
            <template #default="scope">
              <el-progress
                :percentage="scope.row.conversion_rate"
                :color="getProgressColor(scope.row.conversion_rate)"
                :show-text="false"
                :stroke-width="6"
              />
              <div class="conversion-text">
                {{ scope.row.conversion_rate.toFixed(1) }}%
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="last_sale_time" label="最近销售" width="150">
            <template #default="scope">
              <span v-if="scope.row.last_sale_time">
                {{ formatDateTime(scope.row.last_sale_time) }}
              </span>
              <span v-else class="no-sales">暂无销售</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="handleViewDetail(scope.row)">
                <el-icon><View /></el-icon>
                查看详情
              </el-button>
              <el-button
                size="small"
                type="primary"
                @click="handleViewTeam(scope.row)"
              >
                <el-icon><UserFilled /></el-icon>
                团队
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 无数据提示 -->
      <div v-if="!loading && rankingList.length === 0" class="no-data">
        <el-empty description="暂无卡密售卖数据" />
      </div>
    </el-card>

         <!-- 今日卡密售卖趋势图表 -->
     <el-card class="chart-card" style="margin-top: 20px">
       <template #header>
         <span>今日卡密售卖趋势图</span>
       </template>
      <div id="salesTrendChart" style="height: 400px"></div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElLoading } from "element-plus";
import {
  Refresh,
  Download,
  Trophy,
  Medal,
  View,
  UserFilled,
} from "@element-plus/icons-vue";
import { getAgentSalesRanking } from "@/api/statistics";
import { useUserStore } from "@/store/user";
import * as echarts from "echarts";

const router = useRouter();
const userStore = useUserStore();
const loading = ref(false);
const rankingList = ref([]);
const dateRange = ref([]);
let chartInstance = null;

const queryParams = reactive({
  period: "today", // 默认显示今天的数据
  limit: 5, // 默认前5名
  start_date: "",
  end_date: "",
});

const overviewStats = reactive({
  totalAgents: 0,
  totalSales: 0,
  totalRevenue: 0,
  avgSales: 0,
});

// 获取销量排行榜数据
const getRankingData = async () => {
  loading.value = true;
  try {
    const res = await getAgentSalesRanking(queryParams);
    if (res.code === 0) {
      rankingList.value = res.data.ranking || [];

      // 更新概览统计
      Object.assign(overviewStats, res.data.overview || {});

      // 渲染图表
      nextTick(() => {
        renderChart(res.data.chartData || []);
      });
    } else {
      ElMessage.error(res.message || "获取排行榜数据失败");
    }
  } catch (error) {
    console.error("获取排行榜数据失败", error);
    ElMessage.error("获取排行榜数据失败");
  } finally {
    loading.value = false;
  }
};

// 处理日期范围变化
const handleDateRangeChange = (dates) => {
  if (dates && dates.length === 2) {
    queryParams.start_date = dates[0];
    queryParams.end_date = dates[1];
    queryParams.period = ""; // 清空预设周期
  } else {
    queryParams.start_date = "";
    queryParams.end_date = "";
  }
};

// 查询
const handleQuery = () => {
  getRankingData();
};

// 重置查询
const resetQuery = () => {
  queryParams.period = "today"; // 重置为今天
  queryParams.limit = 5; // 重置为前5名
  queryParams.start_date = "";
  queryParams.end_date = "";
  dateRange.value = [];
  getRankingData();
};

// 刷新数据
const handleRefresh = () => {
  getRankingData();
};

// 导出数据
const handleExport = () => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: "正在导出数据...",
    background: "rgba(0, 0, 0, 0.7)",
  });

  // 模拟导出延迟
  setTimeout(() => {
    loadingInstance.close();
    ElMessage.success("数据导出成功");
  }, 2000);
};

// 查看代理详情
const handleViewDetail = (row) => {
  router.push(`/agent/detail/${row.agent_id}`);
};

// 查看代理团队
const handleViewTeam = (row) => {
  router.push(`/agent/team/${row.agent_id}`);
};

// 手机号脱敏处理
const maskMobile = (mobile) => {
  if (!mobile) return "";
  return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
};

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return "";
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
    2,
    "0"
  )}-${String(date.getDate()).padStart(2, "0")} ${String(
    date.getHours()
  ).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
};

// 获取进度条颜色
const getProgressColor = (percentage) => {
  if (percentage >= 80) return "#67c23a";
  if (percentage >= 60) return "#e6a23c";
  if (percentage >= 40) return "#f56c6c";
  return "#909399";
};

// 根据排名获取销售数字的样式类
const getSalesNumberClass = (index) => {
  if (index === 0) return "sales-number-first";   // 第一名
  if (index === 1) return "sales-number-second";  // 第二名
  if (index === 2) return "sales-number-third";   // 第三名
  return "sales-number-normal";                    // 其他
};

// 渲染销量趋势图表
const renderChart = (chartData) => {
  const chartDom = document.getElementById("salesTrendChart");
  if (!chartDom) return;

  if (chartInstance) {
    chartInstance.dispose();
  }

  chartInstance = echarts.init(chartDom);

     const option = {
     title: {
       text: "今日代理卡密售卖趋势",
       left: "center",
     },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        label: {
          backgroundColor: "#6a7985",
        },
      },
    },
    legend: {
      data: ["卡密售卖数量"],
      top: "10%",
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: [
      {
        type: "category",
        boundaryGap: false,
        data: chartData.map((item) => item.date),
      },
    ],
    yAxis: [
      {
        type: "value",
        name: "卡密售卖数量（单）",
        position: "left",
      },
    ],
    series: [
      {
        name: "卡密售卖数量",
        type: "line",
        smooth: true,
        data: chartData.map((item) => item.sales_count),
        itemStyle: {
          color: "#5470c6",
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "rgba(84, 112, 198, 0.3)",
              },
              {
                offset: 1,
                color: "rgba(84, 112, 198, 0.1)",
              },
            ],
          },
        },
      },
    ],
  };

  chartInstance.setOption(option);

  // 响应式调整
  window.addEventListener("resize", () => {
    chartInstance?.resize();
  });
};

onMounted(() => {
  getRankingData();
});
</script>

<style scoped>
.sales-ranking-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.stats-overview {
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 10px;
  color: white;
}

.stats-overview :deep(.el-statistic__content) {
  color: white;
}

.stats-overview :deep(.el-statistic__head) {
  color: rgba(255, 255, 255, 0.8);
}

.ranking-table {
  margin-top: 20px;
}

.ranking-badge {
  display: flex;
  justify-content: center;
  align-items: center;
}

.gold-medal {
  color: #ffd700;
}

.silver-medal {
  color: #c0c0c0;
}

.bronze-medal {
  color: #cd7f32;
}

.rank-number {
  font-weight: bold;
  font-size: 16px;
  color: #666;
}

.agent-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.agent-details {
  flex: 1;
}

.agent-name {
  font-weight: 500;
  color: #303133;
}

.agent-level {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.sales-amount {
  font-weight: bold;
  color: #67c23a;
}

.usage-value {
  font-weight: bold;
  color: #409eff;
}

.commission-amount {
  font-weight: bold;
  color: #e6a23c;
}

.sales-highlight {
  display: flex;
  align-items: baseline;
  justify-content: center;
  gap: 4px;
  margin-bottom: 4px;
}

.sales-number {
  font-size: 32px;
  font-weight: bold;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.sales-number-first {
  color: #ff6b35;
  text-shadow: 0 2px 8px rgba(255, 107, 53, 0.4);
  animation: pulse-first 2s infinite;
}

.sales-number-second {
  color: #f7931e;
  text-shadow: 0 2px 6px rgba(247, 147, 30, 0.4);
}

.sales-number-third {
  color: #ffb84d;
  text-shadow: 0 2px 4px rgba(255, 184, 77, 0.4);
}

.sales-number-normal {
  color: #409eff;
  text-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
}

@keyframes pulse-first {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

.sales-unit {
  font-size: 16px;
  font-weight: 600;
  color: #606266;
}

.sales-note {
  font-size: 11px;
  color: #909399;
  margin-top: 2px;
  background: #f0f9ff;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
}

.conversion-text {
  text-align: center;
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.no-sales {
  color: #c0c4cc;
  font-style: italic;
}

.no-data {
  padding: 40px 0;
  text-align: center;
}

.chart-card {
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-overview {
    padding: 15px;
  }

  .search-box {
    padding: 15px;
  }

  .agent-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style>
